import json
import threading
import time
from datetime import datetime, timedelta
from threading import Event

import requests
from flask import request
from flask_socketio import send

from app1 import app
# from app1 语句要放在 import app1 后面
from app1.wsserver import socketio1

# 定义API请求的相关信息
BASEURL = app.config['S_BASE']

# top10
URL_TOP10 = BASEURL + "ns_sjfxpt/app/top10"

START_THREAD_3 = "SJFX_ALL_START 3"
STOP_THREAD_3 = "SJFX_ALL_STOP 3"
RUNNING_THREAD_3 = "SJFX_ALL_RUNNING"

# 用于停止定时任务的事件
stop_event3 = Event()

# 用于跟踪当前是否有定时请求线程正在运行
current_thread3 = None
thread_lock_3 = threading.Lock()

headers = {
    'accept': 'application/json',
    'Content-Type': 'application/json'
}

# 取一天前的数据
end_date = datetime.now()
# 计算开始时间为当前时间的一个月前
start_date = end_date - timedelta(days=1)

# 默认值
data_payload_3 = {
    "sys": "test999",
    "classify": "txnChannel",
    "stime": str(start_date.strftime('%Y-%m-%d %H:%M:%S')),  # 转字符串 使得可以被序列号
    "etime": str(end_date.strftime('%Y-%m-%d %H:%M:%S'))
}


def parse_thread_command(data):
    parts = data.split()
    print(parts)
    if len(parts) != 2:
        raise ValueError("命令格式不正确。请输入正确格式：'启动线程 3' 或 '停止线程 3'")

    try:
        thread_number = int(parts[1])
    except ValueError:
        raise ValueError("线程号必须是一个数字")

    return parts[0], thread_number


@socketio1.on('message_sjfx')
def handle_message_sjfx(data):
    ip_address = request.remote_addr
    print(f'Received message Sjfx: {ip_address} , {data}')
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    try:
        command, thread_number = parse_thread_command(data["text"])
        if command == START_THREAD_3.split()[0]:
            promptdata = f"{START_THREAD_3.split()[0]} {thread_number}"
            start_thread_3(ip_address, data, thread_number)
        elif command == STOP_THREAD_3.split()[0]:
            promptdata = f"{STOP_THREAD_3.split()[0]} {thread_number}"
            stop_thread_3(ip_address, data, thread_number)
        else:
            raise ValueError("未知命令")
    except ValueError as e:
        print(f"命令错误：{str(e)}")
        promptdata = f"命令错误：{str(e)}"

    message_xjfx = {
        'ip': ip_address,
        'message': f"{promptdata} - {current_time}"
    }
    send(message_xjfx, broadcast=True)


# 启动线程
def start_thread_3(ip_address, data, thread_number):
    global current_thread3

    with thread_lock_3:
        if thread_number == 3:
            if current_thread3 is None or not current_thread3.is_alive():
                stop_event3.clear()
                current_thread3 = threading.Thread(target=periodic_request_3, args=(ip_address, data, stop_event3, 3))
                current_thread3.start()
                print("Thread 3 started....")
            else:
                print("Thread 3 is already running....")


def stop_thread_3(ip_address, data, thread_number):
    global current_thread3

    with thread_lock_3:
        if thread_number == 3:
            if current_thread3 is not None and current_thread3.is_alive():
                stop_event3.set()
                current_thread3.join()
                current_thread1 = None
                print("Thread 3 stopped.")
            else:
                print("No active thread 3 to stop.")


def periodic_request_3(ip_address, original_message, stop_event, thread_number):
    while not stop_event3.is_set():
        if thread_number == 3:
            print("start event....")
            send_request_and_merge_3(ip_address, original_message, thread_number)
            time.sleep(10)  # 每10秒发送一次请求


# 数据分析平台数据
def send_request_and_merge_3(ip_address, original_message, thread_number):
    try:

        # 保存 original_message
        Tmp_original_message = original_message

        print("start C-AMLA")
        data_payload_3["sys"] = "C-AMLA"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"
        # 若时间为空，则使用默认值
        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        print("start AMLMAS-O-KYC-AP")

        # 开始处理所有的组合类型类型
        # AMLMAS-O-KYC-AP	txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "AMLMAS-O-KYC-AP"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"


        print(original_message)
        print("start AMLMAS-O-KYC-AP DEBUG1")
        print(original_message["startTime"])
        print(original_message["endTime"])
        print("start AMLMAS-O-KYC-AP DEBUG5 ")

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            print("start AMLMAS-O-KYC-AP DEBUG4 ")

            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:
            print("start AMLMAS-O-KYC-AP ELSE ")
            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        print("start AMLMAS-O-KYC-AP DEBUG3")

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))



        print("start AMLMAS-O-KYC-AP DEBUG2")

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        print("start AMLMAS-O-KYC-EA")
        # AMLMAS - O - KYC - EA
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "AMLMAS-O-KYC-EA"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        print("start amlmas_am")
        # amlmas_am
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "amlmas_am"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # amlmas_ap
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "amlmas_ap"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # amlmas_ea
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "amlmas_ea"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # bfts
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "bfts"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # bfts_jiaoyi
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "bfts_jiaoyi"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # bfts_jigou
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "bfts_jigou"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # bpsauto
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "bpsauto"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # exn_ccms - d
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "exn_ccms-d"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # ccps - ccs
        # txnChannel
        # 若时间为空，则使用默认值
        data_payload_3["sys"] = "ccps-ccs"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # gilmp
        # txncode
        data_payload_3["sys"] = "gilmp"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txncode"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # bep
        # txncode
        data_payload_3["sys"] = "bep"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txncode"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # PBPS - DMA
        # txncode
        data_payload_3["sys"] = "PBPS-DMA"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txncode"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # TPCC
        # txnChannel
        data_payload_3["sys"] = "TPCC"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")

        # C - AMLA  这个作为第一个默认已有，不进行重新请求
        # txnChannel

        # C - AMLT
        # txnChannel
        data_payload_3["sys"] = "C-AMLT"
        # data_payload_3["sys"] = "test999"
        data_payload_3["classify"] = "txnChannel"

        if original_message["startTime"] == '' or original_message["endTime"] == '':
            # 获取当前时间作为结束时间
            end_date = datetime.now()
            # 计算开始时间为当前时间的一个月前
            start_date = end_date - timedelta(days=1)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str
        else:

            # 将日期字符串转换为 datetime 对象
            # 将带 'T' 的日期字符串转换为 datetime 对象
            start_date = datetime.strptime(original_message["startTime"], '%Y-%m-%d %H:%M:%S')
            end_date = datetime.strptime(original_message["endTime"], '%Y-%m-%d %H:%M:%S')

            print(start_date)

            # 将 datetime 对象格式化为不带 'T' 的字符串
            start_date_str = start_date.strftime('%Y-%m-%d %H:%M:%S')
            end_date_str = end_date.strftime('%Y-%m-%d %H:%M:%S')

            # # 暂存一下 original_message 下面会被替换
            # temp_start_date_str = start_date_str
            # temp_end_date_str = end_date_str

            # 将转换后的日期字符串放入 payload 中
            data_payload_3["stime"] = start_date_str
            data_payload_3["etime"] = end_date_str

        # 发送 POST 请求到指定的URL
        response = requests.post(URL_TOP10, headers=headers, data=json.dumps(data_payload_3))

        # 如果请求成功
        if response.status_code == 200 or response.status_code == 202:
            api_response_data = response.json()  # 获取请求的数据

            # 修改原数据内容
            original_message = RUNNING_THREAD_3

            # 将请求返回的数据合并到 message_with_ip
            message_with_ip = {
                'ip': ip_address,
                'message': original_message,
                'api_response': api_response_data,
                'thread_number': thread_number
            }
            print(f'Final message with IP and API data from Thread {thread_number}: {message_with_ip}')

            # 发送合并后的数据到客户端（广播发送）
            # socketio1.send(message_with_ip, broadcast=True)
            socketio1.send(message_with_ip)
            original_message = Tmp_original_message
        else:
            print(f"Error: Received status code {response.status_code}")


    except Exception as e:
        print(f"Error occurred during API request in Thread {thread_number}: {e}")


@socketio1.on('disconnect')
def handle_disconnect_3():
    stop_event3.set()
